Crate yew_router

source ·
Expand description

Provides routing faculties using the browser history API to build Single Page Applications (SPAs) using Yew web framework.

Usage

use yew::functional::*;
use yew::prelude::*;
use yew_router::prelude::*;

#[derive(Debug, Clone, Copy, PartialEq, Routable)]
enum Route {
    #[at("/")]
    Home,
    #[at("/secure")]
    Secure,
    #[not_found]
    #[at("/404")]
    NotFound,
}

#[function_component(Secure)]
fn secure() -> Html {
    let navigator = use_navigator().unwrap();

    let onclick_callback = Callback::from(move |_| navigator.push(&Route::Home));
    html! {
        <div>
            <h1>{ "Secure" }</h1>
            <button onclick={onclick_callback}>{ "Go Home" }</button>
        </div>
    }
}

#[function_component(Main)]
fn app() -> Html {
    html! {
        <BrowserRouter>
            <Switch<Route> render={switch} />
        </BrowserRouter>
    }
}

fn switch(routes: Route) -> Html {
    match routes {
        Route::Home => html! { <h1>{ "Home" }</h1> },
        Route::Secure => html! {
            <Secure />
        },
        Route::NotFound => html! { <h1>{ "404" }</h1> },
    }
}

Internals

The router registers itself as a context provider and makes location information and navigator available via hooks or RouterScopeExt.

State

The Location API has a way to access / store state associated with session history. Please consult location.state() for detailed usage.

Re-exports

pub use router::BrowserRouter;
pub use router::HashRouter;
pub use router::Router;
pub use switch::Switch;

Modules

Components to interface with Router.
A module that provides universal session history and location information.
Hooks to access router state and navigate between pages.
Prelude module to be imported when working with yew-router.
Router Component.
The Switch Component.

Structs

A special route that accepts any route.

Traits

Marks an enum as routable.

Derive Macros

Derive macro used to mark an enum as Routable.